import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;

/*** class is in charge of running all programs of robots in separate strings ***/
public class Programs {
	
	LinkedList<RunProgram> programs;
	//static Canvas canvas;
	//Shell shell;
	
	//c'tor
	public Programs(){
		programs = new LinkedList<RunProgram>();
		//shell = s;
		//canvas = c;
	}

	/*//timerTask - redraws canvas
	private static class RedrawTask extends TimerTask{
		 Canvas c;
		 Display d;
		 
		 public void setCanvas(Canvas c){
		  this.c=c;
		  d=c.getDisplay();
		 }
		 @Override
		 public void run() {  
			 d.asyncExec(new Runnable(){
				 public void run() {
					 if(!c.isDisposed()){
						 c.redraw();
						 c.update();
					 }
				 }
			 });
		 }
		}
	
	// a thread that runs the timerTask every second
	private class MyThread extends Thread{
	 private RedrawTask rt;
	 private Timer ti;
		public void run(){
		 	rt = new RedrawTask();
		    rt.setCanvas(canvas);
			ti = new Timer();
			ti.scheduleAtFixedRate(rt, 0, 1000);
	     }
	 public void end(){
		 rt.cancel();
		 ti.cancel();
	 }
	}*/
	
	//adds runProgram instance to array list
	public void add(RunProgram rp){
	System.out.println("adding " + rp.fileName);
		rp.getCommands(); //get all command lines from file in rp
		programs.add(rp);
		//if simulation is running then start the program in new thread
		if(GUI.run){
			Thread thread = new Thread(rp);
			thread.start();
		}
	}
	
	//runs all programs - each in separate thread for given amount of seconds
	public void run(){
System.out.println("in run - programs");
		Iterator<RunProgram> programIt = programs.iterator();
		
		//create arrayListof threads for programs
		ArrayList<Thread> threads = new ArrayList<Thread>(programs.size());
		//create list of runProgram objects - fill it up with R.Ps that are finished
		ArrayList<RunProgram> finishedProgs = new ArrayList<RunProgram>(); 
		
		//run all programs
		while(programIt.hasNext()){
			RunProgram rp = programIt.next();
	System.out.println(rp.fileName);
			//if robot completed all of the program - remove it from list
			if(rp.done){
				finishedProgs.add(rp);
			}
			else{
				//rp.setTime(seconds);
				Thread t = new Thread(rp);
				threads.add(t);
				t.start();
		System.out.println("starting on " + rp.fileName);
			}	
		}
	/*	MyThread thread = new MyThread();
		thread.start();
		
		while (!shell.isDisposed()) { 
			if (!canvas.getDisplay().readAndDispatch()) {        
		        canvas.getDisplay().sleep();
		      }
		}
		thread.end();*/
		
		removeFinishedProgs(finishedProgs);
	}
	
	//remove all programs that are finished
	private void removeFinishedProgs(ArrayList<RunProgram> finishedProgs){
		Iterator<RunProgram> programIt = finishedProgs.iterator();
		
		while(programIt.hasNext()){
			RunProgram rp = programIt.next();
			programs.remove(rp);
		}
	}
	
	
	
	

}
